package com.david.cloud.filter;

import com.david.cloud.service.TokenService;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * TODO 权限过滤器
 * 添加全局过滤，进⾏行行token的验证，⽤用户微服务和验证码微服务的请求不不过滤（⽹网关调⽤用下游
 * ⽤用户微服务的token验证接⼝口）
 */
@Slf4j
@Order(1)
@Component
public class AuthFilter implements GlobalFilter {
    @Reference
    private TokenService tokenService;
    List<String> ignorePaths = ImmutableList.of("/user/register", "/user/login", "/code/create");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String requestUri = request.getPath().pathWithinApplication().value();
        //忽略不过滤的url
        boolean present = ignorePaths.stream().anyMatch(requestUri::startsWith);
        if (present) {
            log.info("{} ignore", requestUri);
            return chain.filter(exchange);
        }

        String token = "";
        // 从request对象中获取客户端ip
        Map<String, HttpCookie> cookieMap = request.getCookies().toSingleValueMap();
        HttpCookie cookie = cookieMap.get("token");
        //cookie 存在 且库里有
        if (cookie != null) {
            token = cookie.getValue();
        }
        String headerToken = request.getHeaders().getFirst("token");
        if (!StringUtils.isEmpty(headerToken)) {
            token = headerToken;
        }
        if(!StringUtils.isEmpty(token)){
            Boolean valid = tokenService.getByToken(token);
            if (valid) {
                return chain.filter(exchange);
            }
        }
        //被过滤返回401
        DataBuffer wrap = response.bufferFactory().wrap(HttpStatus.UNAUTHORIZED.getReasonPhrase().getBytes());
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.writeWith(Mono.just(wrap));
    }
}
